package com.guli.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.constant.MqConstant;
import com.guli.common.exception.NoStockException;
import com.guli.common.to.SkuInfoTo;
import com.guli.common.to.mq.StockDetailTo;
import com.guli.common.to.mq.StockLockedTo;
import com.guli.common.utils.R;
import com.guli.ware.entity.WareOrderTaskDetailEntity;
import com.guli.ware.entity.WareOrderTaskEntity;
import com.guli.ware.feign.OrderFeignService;
import com.guli.ware.feign.ProductFeignService;
import com.guli.ware.service.WareOrderTaskDetailService;
import com.guli.ware.service.WareOrderTaskService;
import com.guli.ware.vo.*;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import io.swagger.models.auth.In;
import lombok.Data;
import org.aspectj.weaver.ast.Var;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.ware.dao.WareSkuDao;
import com.guli.ware.entity.WareSkuEntity;
import com.guli.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ProductFeignService productFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public R hasStock(Long skuId) {
        WareSkuEntity wareSku = this.getOne(new QueryWrapper<WareSkuEntity>().in("sku_id", skuId));
        if (wareSku != null) {
            int hasStock = wareSku.getStock() - wareSku.getStockLocked();
            if (hasStock > 0) {
                R.ok().put("data", true);
            }
        }
        return R.ok().put("data", false);
    }

    @Override
    public R hasStocks(List<Long> skuIds) {
        Map<Long, Boolean> map = new HashMap<>();
        List<WareSkuEntity> skus = this.baseMapper
                .selectList(new QueryWrapper<WareSkuEntity>().in("sku_id", skuIds));
        if (CollectionUtils.isEmpty(skus)) {
            return R.ok();
        }
        skus.forEach(sku -> {
            Long skuId = sku.getSkuId();
            int stock = sku.getStock() - sku.getStockLocked();
            map.put(skuId, stock > 0);
        });
        return R.ok().put("data", map);
    }

    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        // 保存库存工作单
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        //拷贝对象
        BeanUtils.copyProperties(wareSkuLockVo, orderTaskEntity);
        //保存对象
        wareOrderTaskService.save(orderTaskEntity);
        //按照下单的收货地址，找到一个就近仓库，锁定库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        //找到每个商品在哪个仓库都有库存
        List<SkuWareHasStock> stockList = locks.stream().map(lock -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = lock.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(lock.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        /*
         * 对每个商品进行锁定
         * */
        for (SkuWareHasStock hasStock : stockList) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            //如果每一个商品都锁定成功，将当前商品锁定了几件的工作单发给MQ
            //锁定失败，前面保存的工作单信息就会滚了，发送出去的消息，
            //即使要解锁记录吗，由于查不到，由于去数据库查不到id，所以不用解锁
            for (Long wareId : wareIds) {
                //成功返回1，否则返回0
                //锁定库存
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    //库存锁定成功
                    skuStocked = true;
                    R skuInfo = productFeignService.skuInfo(skuId);
                    SkuInfoTo skuInfoTo = skuInfo.getData(new TypeReference<SkuInfoTo>() {
                    });
                    //库存锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetail = new WareOrderTaskDetailEntity();
                    //设置skuid
                    wareOrderTaskDetail.setSkuId(skuId);
                    //设置skuName
                    wareOrderTaskDetail.setSkuName(skuInfoTo.getSkuName());
                    //设置仓库ID
                    wareOrderTaskDetail.setWareId(wareId);
                    //设置sku数量
                    wareOrderTaskDetail.setSkuNum(hasStock.getNum());
                    //设置锁定状态
                    wareOrderTaskDetail.setLockStatus(1);
                    //设置工作单id
                    wareOrderTaskDetail.setOrderTaskId(orderTaskEntity.getId());
                    //保存
                    wareOrderTaskDetailService.save(wareOrderTaskDetail);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(orderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetail, stockDetailTo);
                    lockedTo.setStockDetailTo(stockDetailTo);
                    //发送消息到MQ
                    rabbitTemplate.convertAndSend(
                            MqConstant.STOCK_EVENT_EXCHANGE,
                            MqConstant.STOCK_DELAY_ROUTING,
                            lockedTo
                    );
                    //在当前仓库锁定了库存
                    //无需在其他仓库找
                    break;
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        return true;
    }
}
